﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CSKLiteWindowsPhone.WebsiteData;
using SQLiteClient;
using CSKLiteWindowsPhone.Common;
using CSKLiteWindowsPhone.UserContorl;
using System.IO.IsolatedStorage;

namespace CSKLiteWindowsPhone
{
    public partial class TestResultReport : PhoneApplicationPage
    {
        SQLiteConnection _db = null;
        TestResult _currentTestResult = new TestResult();
        string _sessionId = string.Empty;
        IEnumerable<TestCase> testCases = null;
        IEnumerable<TestProcedure> testProcs = null;
        IEnumerable<TestCase> targetTestCases = null;

        public TestResultReport()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.Keys.Contains("sessionid"))
            {
                this._db = Utility.GetConnection();
                this._sessionId = NavigationContext.QueryString["sessionid"];
                SQLiteCommand cmd = this._db.CreateCommand("SELECT * FROM TestCase");
                this.testCases = cmd.ExecuteQuery<TestCase>();

                string sql = string.Format("SELECT * FROM TestSession WHERE Id = '{0}'", this._sessionId);
                cmd = this._db.CreateCommand(sql);

                TestSession testSession = cmd.ExecuteQuery<TestSession>().First();

                var tempResults = IsolatedStorageSettings.ApplicationSettings["CurrentSessionResult"] as List<TestSessionResult>;
                TestSessionResult[] results = tempResults.ToArray();

                List<DetailedResult> detailedResults = new List<DetailedResult>();

                Array.ForEach<TestSessionResult>(results, new Action<TestSessionResult>((result) =>
                {
                    DetailedResult r = new DetailedResult();
                    r.Code = result.Code;
                    r.StepId = result.Sequence;
                    r.TestId = result.TestId;
                    List<ResultType> resultTypes = new List<ResultType>();
                    if (!string.IsNullOrEmpty(result.Type) && !string.IsNullOrEmpty(result.TypeValue))
                    {
                        resultTypes.Add(new ResultType() { Name = result.Type, Value = result.TypeValue });
                    }
                    if (!string.IsNullOrEmpty(result.Type2) && !string.IsNullOrEmpty(result.Type2Value))
                    {
                        resultTypes.Add(new ResultType() { Name = result.Type2, Value = result.Type2Value });
                    }
                    r.ResultTypes = resultTypes.ToArray();
                    detailedResults.Add(r);
                }));

                testSession.DetailedResults = detailedResults.ToArray();

                List<CategoryResult> categoryResults = new List<CategoryResult>();
                var a = from r in results
                        join tp in this.testCases on r.TestId equals tp.Id
                        select new
                        {
                            Code = r.Code,
                            SessionId = r.SessionId,
                            Sequence = r.Sequence,
                            TestId = r.TestId,
                            Type = r.Type,
                            TypeValue = r.TypeValue,
                            Type2 = r.Type2,
                            Type2Value = r.Type2Value,
                            Category = tp.Category
                        };

                var ac = from i in a
                         group i by new { i.Category} into c
                         select new CategoryResult
                         {
                             Category = c.Key.Category,
                             Results = (from r in a
                                        where r.Category == c.Key.Category
                                        group r by r.Code into rg
                                        select new Result1
                                        {
                                            Code = rg.Key,
                                            Count = rg.Count().ToString()
                                        }).ToArray()
                         };


                testSession.CategoryResults = ac.ToArray();
                List<CategoryReportControl> crcs = new List<CategoryReportControl>();
                for (int i = 0; i < testSession.CategoryResults.Count(); i ++ )
                {
                    var item = testSession.CategoryResults[i];
                    CategoryReportControl cr = new CategoryReportControl();
                    cr.Title = item.Category;
                    cr.Name = "CategoryReportControl" + item.Category;

                    List<CircleTile> tiles = new List<CircleTile>();

                    CircleTile circleTile = new CircleTile();
                    circleTile.Title = "Total";
                    circleTile.Name = "CategoryReportControl" + i.ToString() + "CircleTileTotal";
                    int count = 0;

                    foreach (var c in item.Results)
                    {
                        count += int.Parse(c.Count);
                    }

                    circleTile.Text = count.ToString();
                    circleTile.Color = Colors.White;

                    cr.CircleTiles.Add(circleTile);

                    foreach (var tile in item.Results)
                    {
                        CircleTile ct = new CircleTile();
                        ct.Title = tile.Code;
                        ct.Text = tile.Count.ToString();
                        ct.Color = Colors.White;
                        if (tile.Code == "Error")
                        {
                            ct.Color = Colors.Red;
                        }
                        ct.Name = "CategoryReportControl" + i.ToString() + "CircleTile" + tile.Code;

                        cr.CircleTiles.Add(ct);
                    }

                    crcs.Add(cr);
                }

                this.listTestCase.ItemsSource = crcs;
            }
        }

        protected override void OnRemovedFromJournal(System.Windows.Navigation.JournalEntryRemovedEventArgs e)
        {
            base.OnRemovedFromJournal(e);

            this._db.Dispose();
            this._db = null;
        }
    }
}